//
//  AppDelegate.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/9.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit

var sharedUserAccount = UserAccount.loadUserAccount()

let SwitchRootViewControllerNotification = "SwitchRootViewControllerNotification"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        // 实例化 window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor(white: 1, alpha: 1)
        window?.makeKeyAndVisible()
        
        // 设置全局变量
        setAppearance()
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: SwitchRootViewControllerNotification, object: nil)
        
        // 设置主界面
        showMainInterface()
        
        return true
    }
    
    // 所有的根视图切换统一管理
    func switchRootViewController(noti: NSNotification){
        showStoryboard(noti.object as!String)
    }
    
    // 根据storyboard设置显示的根视图
    func showStoryboard(sbName :String){
        let sb = UIStoryboard(name: sbName, bundle: nil)
        window?.rootViewController = sb.instantiateInitialViewController() as? UIViewController
    }
    
    // 主界面的流程
    func showMainInterface(){
        var sbName = "Main"
        
        if sharedUserAccount != nil {
            sbName = isNewUpdate() ? "NewFeature" : "Welcome"
        }
        showStoryboard(sbName)
    }
    
    // 是否最新版本
    func isNewUpdate () -> Bool {
        // 获取当前的版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let versionValue = NSNumberFormatter().numberFromString(currentVersion)!.doubleValue
        
        // 和沙盒中得版本进行比较
        let sandboxKey = "sandboxKey"
        let defaults = NSUserDefaults.standardUserDefaults()
        let sandboxVersion = defaults.doubleForKey(sandboxKey)
        
        // 保存最新的版本
        defaults.setDouble(versionValue, forKey: sandboxKey)
        // 同步
        defaults.synchronize()
        
        return versionValue > sandboxVersion
    }
    
    /// 设置全局外观
    private func setAppearance(){
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }

}

